import globalUrl from '../utils/global.vue'

export default {
  data() {
    return {
      ws: null,
      // 开发环境
      path: globalUrl.wsUrl,
      // path: "ws://192.168.8.15:8081", // 测试环境
      heartTimer: null,
      heartInterval: 1000 * 10,
      isResetFlag: false,
      initErrorInterval: 1000 * 10
    }
  },

  created() {},

  mounted() {
    // this.initSocket();
    // 存在页面刷新 导致socket关闭 需要再次除非
    if (this.globalSocket.ws && !!this.globalSocket.ws.url) {
      return
    }
    // 页面刷新或者是login页面
    if (this.getCookie('token')) {
      // 登录状态 需要重启socket
      this.initSocket()
    }
  },

  beforeDestroy() {
    // this.ws.close();
    // clearInterval(this.heartTimer);
  },

  methods: {
    initSocket() {
      if (typeof WebSocket === 'undefined') {
        alert('您的浏览器不支持socket')
      } else {
        let token = this.getCookie('materialsToken')
        let userId = localStorage.getItem('userId')
        // let useParams = `${UserID}_${token}`
        let useParams = `${userId}`
        // this.ws = null
        // this.globalSocket.setWs(this.ws)
        if (token && userId) {
          this.ws = new WebSocket(this.path + '/imserver/' + useParams)
          this.ws.onopen = this.open
          this.ws.onerror = this.error
          this.ws.onclose = this.closeFn
          this.ws.closeFunc = this.closeFunc
          this.ws.onmessage = this.message
          this.globalSocket.setWs(this.ws)
        } else {
          this.ws = new WebSocket(this.path + '/imserver/ztb')
          this.ws.onopen = this.open
          this.ws.onerror = this.error
          this.ws.onclose = this.closeFn
          this.ws.closeFunc = this.closeFunc
          this.ws.onmessage = this.message
          this.globalSocket.setWs(this.ws)
        }
      }
    },
    // 打开ws之后 打开心跳
    open() {
      console.log('----------webSocket连接成功-------------')
      this.sending()
    },
    // 接受消息 事件总线发布接受消息事件
    message(e) {
      // console.log(e.data)
      // 根据不同类别 对不同的组件页面发布不同的事件
      // 推送消息提醒
      console.log('----------webSocket接受消息-------------')
      this.socketEventBus.$emit('hasGetNewRemind', e.data)
    },

    closeFunc(type) {
      this.closeFn(type)
    },

    closeFn(type) {
      console.log('----------webSocket关闭-------------')
      // websocket 创建实例 连接失败 会进入close事件 且会进入error事件 需要重连
      // websocket 在已经连接的情况下 断网 也会进入close事件 关闭心跳 且重新唤醒
      // 主动关闭 需要关闭心跳

      // error事件触发时 ws实例其实已经创建
      if (this.ws.readyState == 0) {
        // 连接尚未建立
        // 一开始连接 断网情况下 需要设置锁 防止一直唤醒重新连接失败 循环
        if (!this.isResetFlag) {
          this.isResetFlag = true
          let timer = setTimeout(() => {
            this.isResetFlag = false
            this.ws = null
            this.initSocket()
            clearTimeout(timer)
          }, this.initErrorInterval)
        }
      }
      // 连接的情况下 突然断网
      if (this.ws.readyState == 3 && type !== 1) {
        // this.ws.close();
        clearInterval(this.heartTimer)
        this.heartTimer = null
        this.ws = null
        this.globalSocket.setWs(this.ws)
        // 存在断网之后 等待每次重新唤醒的时间间隔内 用户点击退出登录
        let token = this.getCookie('token')
        if (!this.isResetFlag && token) {
          this.isResetFlag = true
          let timer2 = setTimeout(() => {
            this.isResetFlag = false

            this.initSocket()
            clearTimeout(timer2)
          }, this.initErrorInterval)
        }
      } else {
        // 主动关闭
        // this.ws.close();
        clearInterval(this.heartTimer)
        this.heartTimer = null
      }
    },

    // 连接失败重连
    error() {
      // 回调只会在创建实例 连接websocket连接失败回调
      console.log('----------webSocket连接失败重连-------------')
      // this.closeFn();

      // if (this.ws.readyState == 3) {
      //     console.log(111111111111)
      //     this.ws = null;
      //     this.initSocket();
      // }
      // if (!this.isResetFlag) {
      //     console.log(11111111111111111)
      //     this.isResetFlag = true;
      //     let timer = setTimeout(() => {
      //         clearTimeout(timer);
      //         this.initSocket();
      //         this.isResetFlag = false;
      //     }, 100000);
      // }
    },

    // 心跳机制
    sending() {
      clearInterval(this.heartTimer)
      let sendObj = JSON.stringify({ type: -2 })
      this.ws.send(sendObj)
      this.heartTimer = setInterval(() => {
        console.log('----------webSocket心跳机制-------------')
        this.ws.send(sendObj)
      }, this.heartInterval)
    },

    // 抛出的通知服务器事件
    sendMessage(message) {
      const msg = JSON.stringify(message)
      this.globalSocket.ws.send(msg)
    },

    getCookie(userName) {
      if (document.cookie.length > 0) {
        var c_start
        var c_end
        c_start = document.cookie.indexOf(userName + '=')
        if (c_start != -1) {
          c_start = c_start + userName.length + 1
          c_end = document.cookie.indexOf(';', c_start)
          if (c_end == -1) {
            c_end = document.cookie.length
          }
          return unescape(document.cookie.substring(c_start, c_end))
        }
      }
      return ''
    }
  }
}
